package wsi.subgraph.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import org.rygh.core.model.tree.Leaf;
import org.rygh.semantic.model.ex.PredicatePath;
import org.rygh.semantic.model.rdf.Predicate;

public class EntityLeaf extends Leaf<EntityObject, EntityLeaf> {

	private double fusionProbability = -1;

	public EntityLeaf(EntityLeaf parent, EntityObject object) {
		super(parent, object);
	}

	public EntityLeaf duplicateAt(EntityLeaf parent) {
		EntityLeaf new_node = new EntityLeaf(parent, new EntityObject(value));

		if (!isLeaf())
			for (EntityLeaf leaf : getChildren())
				leaf.duplicateAt(new_node);

		return new_node;
	}

	public List<EntityLeaf> getChildren(PredicatePath path) {
		if (isLeaf())
			return null;

		Stack<EntityLeaf> stack = new Stack<>();
		List<EntityLeaf> list = new ArrayList<>();

		stack.push(this);
		int i, len = path.size();

		for (i = 0; i < len; i++) {
			final Predicate pred = path.getPredicate(i);

			list.clear();

			while (!stack.isEmpty()) {
				EntityLeaf n = stack.pop();

				if (!n.isLeaf())
					for (EntityLeaf child : n.getChildren()) {
						Predicate p = child.getValue().getPredicate();

						if (pred.equals(p))
							list.add(child);
					}
			}

			stack.addAll(list);
		}

		return list;
	}

	public double getFusionProbability() {
		return fusionProbability;
	}

	@Override
	public boolean isRoot() {
		return value.getPredicate() == null;
	}

	public void setFusionProbability(double fusionProbability) {
		this.fusionProbability = fusionProbability;
	}

}
